const knex = require('../db/knex');
class OrderModel {
  static async createOrder(userId, totalAmount, paymentMethod) {
    const result = await knex('orders').insert({
      user_id: userId,
      total_amount: totalAmount,
      payment_method: paymentMethod
    });

    // 获取插入的订单 ID
    const orderId = result[0];
    const order = await knex('orders').where({ order_id: orderId }).first();

    return order;
  }

  static async updateOrderStatus(orderId, status) {
    await knex('orders')
      .where({ order_id: orderId })
      .update({ order_status: status });

    return await knex('orders').where({ order_id: orderId }).first();
  }

  static async getOrderById(orderId) {
    return await knex('orders')
      .where({ order_id: orderId })
      .first();
  }

  static async getUserOrders(userId) {
    return await knex('orders')
      .where({ user_id: userId })
      .select(
        'order_id',
        'total_amount',
        'payment_method',
        'order_status',
        'created_at'
      );
  }

  static async cancelOrder(orderId) {
    await knex('orders')
      .where({ order_id: orderId })
      .update({ order_status: 'cancelled' });

    return await knex('orders').where({ order_id: orderId }).first();
  }
}

module.exports = OrderModel;